java如何处理异常并向SSE客户端发送错误
我正在使用Spring的SseEmitter
实现与SSE合作。
在我的例子中,我希望在服务器端找不到项目时处理错误,并发送带有错误消息的事件
我的第一个想法是从服务的方法中抛出一个异常,然后在用@ControllerAdvice
注释的类中通过@ExceptionHandler
处理它。这不起作用,因为@ControllerAdvice
类对SSE客户机一无所知
之后,我尝试了以下代码:
private void sendError(String message, int status) {
log.error("Processing report {} stopped with error '{}'", getContextLogMessage(), message);
sseEmitter.completeWithError(new ApiError(message, HttpStatus.resolve(status)));
sseEmitter.onCompletion(this::stopSelf);
}
但SSE客户收到了下一条消息:
Received error
Event { type: 'error', status: 500, message: '' }
看起来Spring的默认错误消息已发送到SSE客户端
我的SSE客户代码:
const EventSource = require('eventsource')
const eventSource = new EventSource('http://localhost:8080/testing')
eventSource.onmessage = (e) => {
const data = JSON.parse(e.data)
if (data.status == null) {
console.log(data)
} else if (data.status === 'DONE') {
console.log(data.status);
eventSource.close()
} else {
console.log('status = ' + data.status)
}
}
eventSource.onerror = (e) => {
console.log('Received error')
console.log(e)
eventSource.close()
}
我的问题是-是否存在通过@ExceptionHandler
处理它的可能性?也许我误解了Spring的SSE,我以前只使用过sseEmitter.send()
共 (0) 个答案